<!-- 1、定义then方法，接手两个参数，分别是：onFulfilled、onRejected
2、判断状态，如果是fulfilled，执行onFulfilled
3、判断状态，如果是rejected，执行onRejected
4、同时判断传入的是否是函数，如果不是函数，需要对其进行类型转换 -->

<script>
  const PENDING = 'pending'
  const FULFILLED = 'fulfilled'
  const REJECTED = 'rejected'
  class MyPromise {
    constructor(executor) {
      this.state = PENDING
      this.result = undefined
      const resolve = (result) => {
        if (this.state === PENDING) {
          this.state = FULFILLED
          this.result = result
        }
      }
      const reject = (result) => {
        if (this.state === PENDING) {
          this.state = REJECTED
          this.result = result
        }
      }
      executor(resolve, reject)
    }

    then(onFulfilled, onRejected) {
      onFulfilled =
        typeof onFulfilled === 'function' ? onFulfilled : (value) => value
      onRejected =
        typeof onRejected === 'function'
          ? onRejected
          : (reason) => {
              throw reason
            }
      if (this.state === FULFILLED) {
        onFulfilled(this.result)
      }
      if (this.state === REJECTED) {
        onRejected(this.result)
      }
    }
  }

  const p1 = new MyPromise((resolve, reject) => {
    resolve(1)
  })
  p1.then((res) => {
    console.log(res)
  })
   p1.then((res) => {
    console.log(res)
  })
</script>
